#include "simmark.h"

#include "graphicitemcommon.h"

#include <QtGui/QFontMetrics>

using namespace swp;

SimMark::SimMark(qreal radiusLimit, Type type, const QString& text,
    QGraphicsItem* parent) : EllipseGraphicItem(true, false, parent),
        m_radiusLimit(radiusLimit),
        m_text(0)
{
    m_text = new QGraphicsSimpleTextItem(text, this);

    checkForElide(text);

    setPen(QPen(Qt::black, 2));
    setBrush(type == SimMark::Cost ? QBrush(QColor(157, 224, 255, 200)) :
        QBrush(QColor(255, 199, 157, 200)));
}

SimMark::~SimMark()
{

}

void SimMark::setText(const QString& text)
{
    m_text->setText(text);

    checkForElide(text);
}

void SimMark::checkForElide(const QString& text)
{
    QRectF _rect = m_text->boundingRect();

    const qreal max = qMax(_rect.width(), _rect.height());
    if (max > (m_radiusLimit - PREFERRED_CONTENT_PADDING_SMALL) * 2)
    {
        QFontMetrics metrics(m_text->font());
        const QString _text =
            metrics.elidedText(text, Qt::ElideRight,
                int((m_radiusLimit - PREFERRED_CONTENT_PADDING_SMALL) * 2));

        m_text->setText(_text);

        QRectF thisRect = rect();
        thisRect.setWidth(m_radiusLimit * 2);
        thisRect.setHeight(m_radiusLimit * 2);

        setRect(thisRect);
    }
    else
    {
        QRectF thisRect = rect();
        thisRect.setWidth(max + 2 * PREFERRED_CONTENT_PADDING_SMALL);
        thisRect.setHeight(max + 2 * PREFERRED_CONTENT_PADDING_SMALL);

        setRect(thisRect);
    }

    _rect = m_text->boundingRect();

    m_text->setPos((rect().width() - _rect.width()) / 2,
        (rect().height() - _rect.height()) / 2);
}
